package top.hypnos.bigdata.filesystem;

import top.hypnos.bigdata.filesystem.record.ObjectInputStream;
import top.hypnos.bigdata.filesystem.record.ObjectOutputStream;
import top.hypnos.bigdata.filesystem.record.Record;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 内存数据节点
 */
public class MemDataNode implements Record {

    private int txnId;

    private String path;

    private byte[] data;

    private MemDataNode parent;

    private final List<MemDataNode> children = new ArrayList<>();

    public MemDataNode() {
    }

    public MemDataNode(int txnId, String path, byte[] data) {
        this.txnId = txnId;
        this.path = path;
        this.data = data;
    }

    public int getTxnId() {
        return txnId;
    }

    public void setTxnId(int txnId) {
        this.txnId = txnId;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
    }

    public MemDataNode getParent() {
        return parent;
    }

    public void setParent(MemDataNode parent) {
        this.parent = parent;
    }

    public List<MemDataNode> getChildren() {
        return children;
    }

    @Override
    public void serialize(final ObjectOutputStream output) throws IOException {
        output.writeInt(txnId);
        output.writeString(path);
        output.writeBytes(data);
        output.writeInt(children.size());
        for (final var child : children) {
            child.serialize(output);
        }
    }

    @Override
    public void deserialize(final ObjectInputStream input) throws IOException {
        txnId = input.readInt();
        path = input.readString();
        data = input.readBytes();
        final var childrenSize = input.readInt();
        for (int i = 0; i < childrenSize; i++) {
            final var child = new MemDataNode();
            child.deserialize(input);
            child.setParent(this);
            children.add(child);
        }
    }
}
